<?php
class PayController extends AppController {

	public $name = 'pay';

	function beforeFilter() {
	    parent::beforeFilter(); 
		$this->C_auth->autoRedirect = false; //For override login
	    $this->C_auth->allowedActions = array('index','respond','paymsg','surerecevi');

	}
	
	public function surerecevi() {
        $this->_teamRights();	
        $order_id = intval($_GET['order_id']);
        $type = $_GET['type'];		
        $filename = $_GET['filename'];		
        if(!$order_id) {
	        $order_id = intval($_POST['order_id']);
        }
        if(!$order_id) {exit("Error");}
		require(APP_ROOT . "/app/vendors/surerecevi/".$type."/".$filename.".php");		
		exit;		
    }	
	
	public function index() {
        $order_id = intval($_GET['order_id']);
        $pay_id = intval($_GET['pay_id']);
        $shop_id = intval($_GET['shop_id']);
        isset($_GET["action"])?$action = $_GET["action"] :$action = '';
        if(!$order_id) { exit("非法操作"); }
        if(!$pay_id) { exit("非法操作"); }	
	    $nowtime = date("Y-m-d H:i:s",time());
		$user_id = $this->my->id;
		$query = array(
				'joins' => array(
				array('type'=>'left','table'=>'payment','conditions'=>array('shoppayment.pay_id' =>'payment.id')),										
				),
				'fields' => array('shoppayment.*','payment.*'),
				'conditions' => array('shoppayment.shop_id' =>$shop_id,'shoppayment.pay_id' =>$pay_id),
			);	
	    $rowset = POP::exe('[@@:UM shoppayment][@@:QU find:all]',$query);			
		
		
		$rowset = array_merge($rowset['0']['a'], $rowset['0']['b']);		
	    $pay_info = array();
	    $temp = unserialize($rowset['pay_config']);
	    if(is_array($temp)){
		    $pay_info = array_merge($rowset, $temp);
	    }
        if($pay_info['enabled']=='0'){
	        exit("非法操作！");
        }
        if($pay_id=='4'||$pay_id=='5'){
		    require(APP_ROOT . "/app/vendors/payment/".$pay_info['pay_code']."/".$pay_info['pay_code'].".php");
		    //Loader::import('app.vendors.payment.'.$pay_info['pay_code'].'.'.$pay_info['pay_code']);
	        exit;
        }
         if($action == 'money_append'){  //用户充值
/*	        $info = get_user_account($dbo,$t_user_account,$order_id);
	        //print_r($info);
	        $order_info['message']		= $info['user_note'];
	        $order_info['payid'] 		= rand(1000,9999).str_pad($info['account_id'],6,'0','str_pad_left');
	        $order_info['order_amount'] = $info['money_num'];
	        $order_info['show_url'] 	= $baseUrl."modules.php?app=user_money";

	        require("payment/".$pay_info['pay_code']."/".$pay_info['pay_code'].".php");
	        $update['pay_id'] = $pay_id;
	        $update['tempcode'] = $order_info['payid'];
	        if(update_user_account($dbo,$t_user_account,$update,$info['account_id'])){
		        get_code($order_info,$pay_info);
	        }
	        //print_r($order_info);
	        exit;*/
        }else{	
	        //订单付款
		    $order_info = array();
			$query = array(
					'fields' => array('orderinfo.*'),
					'conditions' => array('orderinfo.id' => $order_id,'orderinfo.user_id' => $user_id),
					);	
			$order_info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);
			
		    if(!$order_info ) { exit('该订单不存在！');  }
		    $order_info = $order_info['orderinfo'];
			$query = array(
					'joins' => array(
					array('type'=>'left','table'=>'shopinfo','conditions'=>array('shopinfo.id' =>'goods.shop_id')),					
					array('type'=>'left','table'=>'ordergoods','conditions'=>array('ordergoods.goods_id' =>'goods.id')),					
					),
					'fields' => array('ordergoods.goods_id','ordergoods.goods_price','ordergoods.order_num','ordergoods.goods_name','ordergoods.id',
			'goods.goods_thumb','shopinfo.user_id','shopinfo.shop_name'),
					'conditions' => array('ordergoods.order_id' =>$order_info['id'],'shopinfo.id' =>$order_info['shop_id']),
				);	
			$list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);				
			
			
			
	        $order_info['order_goods']=$list;			
	        $order_info['show_url'] = "modules.php?app=user_order_view&order_id=".$order_info['id'];
	        require(APP_ROOT . "/app/vendors/payment/".$pay_info['pay_code']."/".$pay_info['pay_code'].".php");
	
	        $update['pay_id'] = $pay_id;
	        $update['pay_time'] = $nowtime;
	        $order_info['order_amount'] = $order_info['order_value'];
			$query  = array();		
			$query['keyid'] = $order_id;
			$safeData['orderinfo'] = $update;				
			$query['set'] = $safeData;			
	        if(POP::exe('[@@:UM orderinfo][@@:QU save]',$query)){
		        get_code($order_info,$pay_info);
	        }
        } 	
	}	

	public function respond() {
	    $user_id = $this->my->id;
        $user_name = $this->my->username;
        //取得返回的订单号
        $pay_code = get_payment_code();
        if(!$pay_code){
	        exit("非法请求");
        }
        if(strlen($pay_code) != 16){	//用户充值
/* 	        $account_id = intval(substr($pay_code,4));
	        $info = get_user_account($dbo,$t_user_account,$account_id);
	        $pay_info = get_one_shopandpayment($dbo,$t_shop_payment,$t_payment,$shop_id,$info['pay_id']);
	        $order_info['message'] 		= $info['user_note'];
	        $order_info['payid']		= $info['tempcode'];
	        $order_info['order_amount'] = $info['money_num'];
	        $order_info['show_url'] 	= "modules.php?app=user_money";

	        if(!$order_info or !$pay_info){
		        exit("订单不存在");
	        }else{
		        require("payment/".$pay_info['pay_code']."/".$pay_info['pay_code'].".php");
		        $result = respond($order_info,$pay_info);
		        if($result == 1){		//买家付款成功
			        dbtarget('w',$dbServs);
			        if($info['is_verify'] == 0){
				        $sql = "update `$t_users` set user_money = user_money+$info[money_num] where user_id = $info[user_id] ";
				        $dbo->exeUpdate($sql);
			        }

			        $verify_time = $ctime->long_time();
			        $sql = "update `$t_user_account` set is_verify=1,verify_time='$verify_time' where account_id='".$info['account_id']."'";
			        $dbo->exeUpdate($sql);

			        echo $m_langpackage->m_pay_success."！<a href=\"".$baseUrl."modules.php?app=user_my_order\">$m_langpackage->m_click_to_money</a>";
		       }else if($result == 0){	//交易失败
			       echo $m_langpackage->m_pay_lose."！<a href=\"".$baseUrl."modules.php?app=user_money\">$m_langpackage->m_click_to_money</a>";
		       }
	        } */
        }else{							//订单付款
		    $order_info = array();
			$query = array(
					'fields' => array('orderinfo.*'),
					'conditions' => array('orderinfo.payid' => $pay_code),
					);	
			$order_info = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);			

			
	        $order_info = $order_info['orderinfo'];

			$query = array(
					'joins' => array(
					array('type'=>'left','table'=>'payment','conditions'=>array('shoppayment.pay_id' =>'payment.id')),										
					),
					'fields' => array('shoppayment.*','payment.*'),
					'conditions' => array('shoppayment.shop_id' =>$order_info['shop_id'],'shoppayment.pay_id' =>$order_info['pay_id']),
				);	
			$rowset = POP::exe('[@@:UM shoppayment][@@:QU find:all]',$query);				
			
			
		    $rowset = array_merge($rowset['0']['a'], $rowset['0']['b']);		
	        $pay_info = array();
	        $temp = unserialize($rowset['pay_config']);
	        if(is_array($temp)){
		        $pay_info = array_merge($rowset, $temp);
	        }			
	        $order_info['show_url'] = "modules.php?app=user_order_view&order_id=".$order_info['id'];
	        if(!$order_info or !$pay_info){
		        exit("订单不存在");
	        }else{

		        require(APP_ROOT . "/app/vendors/payment/".$pay_info['pay_code']."/".$pay_info['pay_code'].".php");

		        $result = respond($order_info,$pay_info);
		        if($result == 1){		//买家付款成功

			        //获取赠送的积分
//			$order_goods = get_order_goods($dbo,$t_order_goods,$order_info['order_id']);
//			$goods_id = get_arr_goods_id($order_goods);
//			$coin = get_goods_coin($dbo,$t_goods,$goods_id);
			        if($order_info['pay_status']==0){
				        $pay_time = date("Y-m-d H:i:s",time());
						$query  = array();		
						$query['keyid'] = true;
						$safeData['orderinfo'] = array('pay_status'=>1,'pay_time'=>$pay_time);				
						$query['set'] = $safeData;	
						$query['conditions'] = array('orderinfo.payid'=>$order_info['payid']);		
						POP::exe('[@@:UM orderinfo][@@:QU save]',$query);						

//				foreach($coin as $value){
//					$sql = "update `$t_users` set points = points+$value[points],coin = coin+$value[coin] where user_id = $order_info[user_id]";
//					$dbo->exeUpdate($sql);
//				}
			       }
			       echo "支付成功.！<a href=\"modules.php?app=user_my_order\">支付成功</a>";

		        }else if($result == 2){	//卖家发货成功

			        $shipping_time = date("Y-m-d H:i:s",time());
					$query  = array();		
					$query['keyid'] = true;
					$safeData['orderinfo'] = array('transport_status'=>1,'shipping_time'=>$shipping_time);				
					$query['set'] = $safeData;	
					$query['conditions'] = array('orderinfo.payid'=>$order_info['payid']);		
					POP::exe('[@@:UM orderinfo][@@:QU save]',$query);						

		        }else if($result == 3){	//买家收货确认，交易成功

			        $receive_time = date("Y-m-d H:i:s",time());
					$query  = array();		
					$query['keyid'] = true;
					$safeData['orderinfo'] = array('pay_status'=>3,'receive_time'=>$receive_time);				
					$query['set'] = $safeData;	
					$query['conditions'] = array('orderinfo.payid'=>$order_info['payid']);		
					POP::exe('[@@:UM orderinfo][@@:QU save]',$query);					

		        }else if($result == 0){	//交易失败
			        echo "支付失败！<a href=\"modules.php?app=user_my_order\">支付失败</a>";
		        }

	        }
        }

	}

	public function paymsg() {	
        $user_id = $this->my->id;
        $nowtime = date("Y-m-d H:i:s",time());
        $order_id = intval(get_args('id'));
        $post['orderinfo']['pay_message'] = get_args('pay_message');
        $post['orderinfo']['pay_id'] = intval(get_args('pay_id'));
        $post['orderinfo']['pay_name'] = get_args('pay_name');
        $post['orderinfo']['pay_status']=1;
        $post['orderinfo']['pay_time']=$nowtime;	
		$rs = array();		
		$query = array(
				'fields' => array('orderinfo.*'),
				'conditions' => array('orderinfo.id' => $order_id),
				);	
		$rs = POP::exe('[@@:UM orderinfo][@@:QU find:first]',$query);			

		$rs = $rs['orderinfo'];
        if($rs['user_id'] != $user_id){
		   exit("您不能删除该内容，您没有这个权利！");
        }
		$query  = array();		
		$query['keyid'] = $order_id;				
		$query['set'] = $post;			
	    if(POP::exe('[@@:UM orderinfo][@@:QU save]',$query)){
		    $this->flash("执行成功！", Router::url('user/usermyorder/'));
		}else {
		    $this->flash("执行失败！", Router::url('user/usermyorder/'));
		}
		
	}	
	
}
//对表单的统一处理
function get_args($name)
{
	if(isset($_GET[$name]))return $_GET[$name];
	if(isset($_POST[$name]))return $_POST[$name];
	return null;
}
function get_payment_code(){
	$code_arr = array('out_trade_no','sp_billno','v_oid','c_order','orderId','balance_id');
	foreach($code_arr as $value){
		if(get_args($value)){
			return get_args($value);
		}
	}
}
?>